<template>
	<view class="login-container">
		<!-- Logo和标题 -->
		<view class="logo-section">
			<view class="logo"></view>
			<text class="app-title">六堡商城</text>
		</view>

		<!-- 登录按钮 -->
		<view class="login-section">
			<button class="auth-btn" open-type="getUserInfo" @getuserinfo="onGetUserInfo" :disabled="authLoading">
				{{ authLoading ? '授权中...' : '微信授权登录' }}
			</button>
		</view>

		<!-- 用户协议 -->
		<view class="agreement-section">
			<view class="agreement-checkbox" @click="toggleAgreement">
				<text class="checkbox" :class="{ checked: agreedToTerms }">{{ agreedToTerms ? '✓' : '' }}</text>
				<text class="agreement-text">
					我已阅读并同意
					<text class="agreement-link" @click.stop="viewUserAgreement">《用户协议》</text>
					和
					<text class="agreement-link" @click.stop="viewPrivacyPolicy">《隐私政策》</text>
				</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'

	export default {
		data() {
			return {
				authLoading: false,
				agreedToTerms: false,
				wxUserInfo: {},
				shopLogo: '/static/images/logo.png',
				isBack: false
			}
		},

		computed: {
			...mapGetters(['isLogin', 'openid', 'directid', 'dealerInfo'])
		},

		onLoad(options) {
			// 检查是否已经登录
			if (options.isBack) {
				this.isBack = options.isBack;
			}
			if (this.dealerInfo && this.dealerInfo.shop_logo && this.dealerInfo.shop_logo !== '') {
				this.shopLogo = this.$tools.buildUrl(this.dealerInfo.shop_logo)
			}
			this.checkLoginStatus()
		},

		methods: {
			// 检查登录状态
			checkLoginStatus() {
				// 使用vuex中的登录状态
				if (this.isLogin && this.openid && this.openid != '') {
					// 已经登录，直接跳转到首页
					this.redirectToHome()
				}
			},

			// 微信授权获取用户信息
			onGetUserInfo(e) {
				if (!this.agreedToTerms) {
					uni.showToast({
						title: '请先同意用户协议',
						icon: 'none'
					})
					return
				}

				if (e.detail.errMsg === 'getUserInfo:ok') {
					this.authLoading = true

					// 获取用户信息
					this.wxUserInfo = e.detail.userInfo
					console.log('获取用户信息', this.wxUserInfo)

					// 获取登录凭证
					uni.login({
						success: (loginRes) => {
							if (loginRes.code) {
								this.performLogin(loginRes.code)
							} else {
								this.authLoading = false
								uni.showToast({
									title: '登录失败，请重试',
									icon: 'none'
								})
							}
						},
						fail: () => {
							this.authLoading = false
							uni.showToast({
								title: '登录失败，请重试',
								icon: 'none'
							})
						}
					})
				} else {
					uni.showToast({
						title: '需要授权才能使用',
						icon: 'none'
					})
				}
			},

			// 执行登录
			async performLogin(code) {
				try {
					// 获取用户登录信息					
					this.$api.user.userRegister({
						auth_code: code,
						nickname: this.wxUserInfo.nickName || '微信用户',
						avatar_url: this.wxUserInfo.avatarUrl || '',
						directid: this.directid,
					}).then(res => {
						// 登录成功的返回数据
						const newUserInfo = res.data
						const openid = newUserInfo.openid
						// 使用vuex保存登录信息
						this.$store.dispatch('login', {
							openid: openid,
							userInfo: newUserInfo
						})

						// 同时保存到本地存储（兼容性）
						// uni.setStorageSync('openid', openid)
						// uni.setStorageSync('userInfo', newUserInfo)

						this.authLoading = false

						uni.showToast({
							title: '登录成功',
							icon: 'success'
						})

						// 跳转页面
						const pages = getCurrentPages()
						const prevPage = pages[pages.length - 2]
						if (this.isBack && prevPage) {
							// 回退上一页
							this.redirectToBack()
						} else {
							// 跳转到首页
							this.redirectToHome()
						}
					})
				} catch (error) {
					this.authLoading = false
					uni.showToast({
						title: '登录失败，请重试',
						icon: 'none'
					})
				}
			},

			// 跳转到首页
			redirectToHome() {
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/index/index'
					})
				}, 1000)
			},

			// 回退上一页
			redirectToBack() {
				setTimeout(() => {
					uni.navigateBack()
				}, 1000)
			},

			// 切换协议同意状态
			toggleAgreement() {
				this.agreedToTerms = !this.agreedToTerms
			},

			// 查看用户协议
			viewUserAgreement() {
				uni.navigateTo({
					url: '/pages/agreement/user-agreement'
				})
			},

			// 查看隐私政策
			viewPrivacyPolicy() {
				uni.navigateTo({
					url: '/pages/agreement/privacy-policy'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.login-container {
		min-height: 100vh;
		background: #ffffff;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 40rpx;
		box-sizing: border-box;
	}

	/* Logo区域 */
	.logo-section {
		text-align: center;
		margin-bottom: 120rpx;
	}

	.logo {
		width: 120rpx;
		height: 120rpx;
		border-radius: 24rpx;
		background: #52a58a;
		background-image: url(@/static/images/logo.png);
		background-size: cover;
		background-position: center center;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 auto 40rpx;
	}

	.logo-text {
		font-size: 48rpx;
		font-weight: bold;
		color: white;
	}

	.app-title {
		font-size: 48rpx;
		font-weight: bold;
		color: #333;
	}

	/* 登录区域 */
	.login-section {
		width: 100%;
		max-width: 600rpx;
		margin-bottom: 80rpx;
	}

	.auth-btn {
		width: 100%;
		height: 88rpx;
		background: #52a58a;
		color: white;
		border: none;
		border-radius: 44rpx;
		font-size: 32rpx;
		font-weight: bold;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.auth-btn:disabled {
		opacity: 0.6;
	}

	/* 用户协议 */
	.agreement-section {
		width: 100%;
		max-width: 600rpx;
	}

	.agreement-checkbox {
		display: flex;
		align-items: flex-start;
		justify-content: center;
	}

	.checkbox {
		width: 32rpx;
		height: 32rpx;
		border: 2rpx solid #ddd;
		border-radius: 6rpx;
		margin-right: 16rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 20rpx;
		color: white;
		flex-shrink: 0;
		margin-top: 4rpx;
	}

	.checkbox.checked {
		background: #52a58a;
		border-color: #52a58a;
		color: white;
	}

	.agreement-text {
		font-size: 24rpx;
		color: #666;
		line-height: 1.6;
	}

	.agreement-link {
		color: #52a58a;
		text-decoration: underline;
	}

	/* 适配底部安全区域 */
	.login-container {
		padding-bottom: calc(40rpx + env(safe-area-inset-bottom));
	}
</style>